package com.qiche.controller.mini;

import com.qiche.aspect.Result;
import com.qiche.constant.PayStatus;
import com.qiche.dto.*;
import com.qiche.enums.ResultEnum;
import com.qiche.enums.SubscribeStatusEnum;
import com.qiche.exception.MySystemException;
import com.qiche.model.*;
import com.qiche.requestpram.SaveSubscribeURL;
import com.qiche.service.*;
import com.qiche.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import java.util.Date;
import java.util.List;

/**
 * 微信小程序端 预约管理控制器
 * @Author: Linzewen
 * @Date: 2018/5/7 0007 15:44
 */
@RestController
@RequestMapping(value = "subscribe/mini")
public class SubscribeMiniController {
    @Autowired
    private SubscribeService subscribeService;

    @Autowired
    private SubscribeProductService subscribeProductService;
    @Autowired
    private StoreMemberService storeMemberService;
    @Autowired
    private ServiceItemWorkstageService serviceItemWorkstageService;
    @Autowired
    private WorkstageService workstageService;
    @Autowired
    private StoreMemberCarService storeMemberCarService;


    /**
     * 预约记录
     * @param pageNo
     * @param pageSize
     * @param status 0：预约中  1：已开单  -1：已取消    （2：全部）
     * @return
     */
    @GetMapping("/subscribeList")
    public Result userGetSubscribeList(@RequestParam(required = false, defaultValue = "1") int pageNo,
                                       @RequestParam(required = false, defaultValue = "10") int pageSize,@RequestParam Integer status) {
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }

        UserSubscribeDto userSubscribeDto = subscribeService.userAllSubscribe(currentUser, pageNo, pageSize,status);
        return Result.createByResultEnum(ResultEnum.SUCCESS, userSubscribeDto);

    }

    /**
     * 服务记录
     * @param pageNo
     * @param pageSize
     * @param status   1：待结算  2：已结算 -1：已取消  （0：全部）
     * @return
     */
    @GetMapping("/serviceList")
    public Result userGetServiceList(@RequestParam(required = false, defaultValue = "1") int pageNo,
                                     @RequestParam(required = false, defaultValue = "10") int pageSize,
                                     @RequestParam Integer status) {
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }
        UserSubscribeDto userSubscribeDto = subscribeService.userAllService(currentUser, pageNo, pageSize,status);
        return Result.createByResultEnum(ResultEnum.SUCCESS, userSubscribeDto);

    }

    /**
     * 门店小程序根据ID获取预约信息
     * @param subcribeId
     * @return
     */
    @GetMapping("/user/{subcribeId}")
    public Result userGetSubscribeDetail(@PathVariable Long subcribeId) {

        Subscribe subscribe = subscribeService.selectByKey(subcribeId);
        if (subscribe == null) {
            return Result.createByResultEnum(ResultEnum.SUBSCRIBE_NOT_EXIST_ERROR);
        }
        UserSubscribeDetaiDto userSubscribeDetaiDto = subscribeService.userSubscribeDetail(subscribe);
        return Result.createByResultEnum(ResultEnum.SUCCESS, userSubscribeDetaiDto);
    }

    /**
     * 根据状态获取预约列表
     * @param pageNo
     * @param pageSize
     * @param subscribeStatus
     * @return
     */
    @GetMapping("/subscribeStatus")
    public Result userGetSubscribeListByStatus(@RequestParam(required = false, defaultValue = "1") int pageNo,
                                               @RequestParam(required = false, defaultValue = "10") int pageSize,
                                               @RequestParam(name = "subscribeStatus") Byte subscribeStatus) {
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }

        UserSubscribeDto userSubscribeDto = subscribeService.userSubscribeByStatus(currentUser, subscribeStatus, pageNo,
                pageSize);
        return Result.createByResultEnum(ResultEnum.SUCCESS, userSubscribeDto);
    }


    /**
     * 根据客户ID获取客户所有预约记录
     * @param customerId
     * @return
     */
    @GetMapping("/customer/list/{customerId}")
    public Result userGetMemberSimpleSubscribes(@PathVariable("customerId") Long customerId) {
        if (customerId == null) {
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }
        StoreMember storeMember=storeMemberService.selectByKey(customerId);
        if (storeMember == null) {
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }
        List<SimpleSubscribeDto> simpleSubscribeDtos = subscribeService.selectSimpleSubscribeDtoByMember(storeMember);

        return Result.createByResultEnum(ResultEnum.SUCCESS, simpleSubscribeDtos);
    }



    private Result<Subscribe> userAddSubscribeByStatus(User currentUser, Subscribe subscribe, List<Long> productIds, Byte status) throws MySystemException {
        try {
            subscribe.setMerchantId(currentUser.getMerchantId().longValue());
            // 商家添加 工单 初始状态为 开单状态
            subscribe.setSubscribeStatus(status);
            subscribe.setPayStatus(PayStatus.PAY_NON);
            subscribe.setCreateTime(new Date());
            if(subscribe.getSubscribeTime()==null){
            	subscribe.setSubscribeTime(new Date());
            }else{
            	 subscribe.setSubscribeTime(subscribe.getSubscribeTime());
            }
            Result<Subscribe> result = subscribeService.userSubscribe(subscribe, productIds);
            if (result.isSuccess()) {
                return Result.createByResultEnum(ResultEnum.SUCCESS, result.getData());
            } else {
                return Result.createByResultEnum(ResultEnum.FAILURE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new MySystemException(ResultEnum.UNKONW_ERROR);
        }
    }
    /**
     * 新建预约
     * @param saveSubscribeURL
     * @return
     */
    @PostMapping("/user")
    public Result userAddSubscribe(@RequestBody SaveSubscribeURL saveSubscribeURL) {
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }
        if(saveSubscribeURL.getStoreMemberCarId()==null){
            return Result.createByErrorMessage("预约车辆不能为空");
        }

        Result result = saveSubscribeURL.checkParam();

        if (result != null) {
            return result;
        }
        Subscribe subscribe = saveSubscribeURL.getSubscribe();
        subscribe.setCustomerCarId(saveSubscribeURL.getStoreMemberCarId());
        StoreMemberCar storeMemberCar=storeMemberCarService.selectByKey(saveSubscribeURL.getStoreMemberCarId());
        if(storeMemberCar!=null){
            subscribe.setCustomerCarDesc(storeMemberCar.getCarInfo());
            subscribe.setFrameNum(storeMemberCar.getFrameNumber());
            subscribe.setCarNum(storeMemberCar.getPlateNumber());
        }
        List<Long> productIds = saveSubscribeURL.getProductIds();
        if (subscribe.getCustomerId() == null) {
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }
        Byte status = SubscribeStatusEnum.SUBSCRIBING.getStatus();
        try {
            return userAddSubscribeByStatus(currentUser, subscribe, productIds, status);
        } catch (MySystemException e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.UNKONW_ERROR);
        }
    }

    /**
     * 更新服务
     * @param subscribe
     * @return
     */
    @PutMapping("/user")
    public Result userUpdateSubscribe(@RequestBody Subscribe subscribe){

        User currentUser = UserUtils.getCurrentUser();
        if (currentUser==null){
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }
        int i = subscribeService.updateNotNull(subscribe);
        if (i>0){
            return Result.createByResultEnum(ResultEnum.SUCCESS);
        }else {
            return Result.createByResultEnum(ResultEnum.FAILURE);
        }
    }

    /**
     * 直接新建工单 (默认开单状态)
     * @param saveSubscribeURL
     * @return
     */
    @PostMapping("/user/product")
    public Result userAddProduct(@RequestBody SaveSubscribeURL saveSubscribeURL) {
        User currentUser = UserUtils.getCurrentUser();
        Result result = saveSubscribeURL.checkParam();
        if (result != null) {
            return result;
        }
        Subscribe subscribe = saveSubscribeURL.getSubscribe();
        List<Long> productIds = saveSubscribeURL.getProductIds();

        Byte status = SubscribeStatusEnum.OPEN_SUBSCRIBE.getStatus();
        Result<Subscribe> result1=userAddSubscribeByStatus(currentUser, subscribe, productIds, status);
        if(result1.isSuccess()){
            //执行开单操作
            Long subcribeId=result1.getData().getSubscribeId();
            List<SubscribeProduct> subscribeProducts=subscribeProductService.selectBySubscribeId(subcribeId);
            for (SubscribeProduct subscribeProduct: subscribeProducts) {
                //该产品的工序数不为0时执行
                if(workstageService.selectByItemId(subscribeProduct.getProductId()).size()!=0){
                    serviceItemWorkstageService.generateWorkstageBySubproId(subscribeProduct.getSubProId());
                    int stageCount=serviceItemWorkstageService.countBySubproId(subscribeProduct.getSubProId());
                    Subscribe tempSubscribe=new Subscribe();
                    tempSubscribe.setSubscribeId(subcribeId);
                    tempSubscribe.setProgress("0/"+stageCount);
                    int updateCount= subscribeService.updateNotNull(tempSubscribe);
                }
            }
        }
        return result1;

    }

    /**
     * 结算
     * @param subcribeId
     * @return
     */

    @PostMapping("/finish")
    public Result finishSubscribe(Long subcribeId) {
        return subscribeService.updateSubscribeStatus(subcribeId, SubscribeStatusEnum.CLOSE_SUBSCRIBE.getStatus());
    }

    /**
     * 取消预约
     * @param subcribeId
     * @return
     */
    @PostMapping("/cancel")
    public Result cancelSubscribe(Long subcribeId) {
        return subscribeService.updateSubscribeStatus(subcribeId, SubscribeStatusEnum.CANCEL.getStatus());
    }

    /**
     * 开单
     * @param subcribeId
     * @return
     */
    @Transactional
    @PostMapping("/open")
    public Result openSubscribe(Long subcribeId) {
        List<SubscribeProduct> subscribeProducts=subscribeProductService.selectBySubscribeId(subcribeId);
        for (SubscribeProduct subscribeProduct: subscribeProducts) {
            if(workstageService.selectByItemId(subscribeProduct.getProductId()).size()!=0){
                serviceItemWorkstageService.generateWorkstageBySubproId(subscribeProduct.getSubProId());
                int stageCount=serviceItemWorkstageService.countBySubproId(subscribeProduct.getSubProId());
                Subscribe tempSubscribe=new Subscribe();
                tempSubscribe.setSubscribeId(subcribeId);
                tempSubscribe.setProgress("0/"+stageCount);
                int updateCount= subscribeService.updateNotNull(tempSubscribe);
            }

        }
        subscribeService.updateSubscribeStatus(subcribeId, SubscribeStatusEnum.OPEN_SUBSCRIBE.getStatus());
        return Result.createBySuccessMessage("开单成功");
    }


}
